#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include <sys/wait.h>
#include "Task.hpp"

// 先描述
class Channel
{
public:
    Channel(int wfd, pid_t subid)
        : _wfd(wfd), _subid(subid)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }

    void Send(int code)
    {
        ssize_t n = write(_wfd, &code, sizeof(code));
        // if(n != sizeof(code))
        // {
        //     std::cerr << "写入错误" << std::endl;
        // }
        (void)n;
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;//不处理返回值，正常情况都会回收成功
    }

    int Fd()
    {
        return _wfd;
    }

    pid_t Subid()
    {
        return _subid;
    }

    std::string Name()
    {
        return _name;
    }

    ~Channel() {}

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

// 再组织
class ChannelManager
{
public:
    ChannelManager() {}

    void Insert(int wfd, int subid)
    {
        _channels.emplace_back(wfd, subid);
    }

    Channel& Select()
    {
        auto& c = _channels[_next++];
        _next %= _channels.size();
        return c;
    }

    void CloseFd()
    {
        for(auto& channel : _channels)
        {
            channel.Close();
            std::cout << "关闭:" << channel.Name() << std::endl; 
        }
    }

    void WaitSubid()
    {
        for(auto& channel : _channels)
        {
            channel.Wait();
            std::cout << "回收:" << channel.Name() << std::endl;
        }
    }

    void CloseAndWait()
    {
        for(auto& channel : _channels)
        {
            channel.Close();
            std::cout << "关闭:" << channel.Name() << std::endl; 
            channel.Wait();
            std::cout << "回收:" << channel.Name() << std::endl;
        }
    }

    void CloseAll()
    {
        for(int i = _channels.size()-1; i >= 0; i--)
        {
            _channels[i].Close();
        }
    }

    ~ChannelManager() {}

private:
    std::vector<Channel> _channels;
    int _next = 0;
};

const int gdefaultnum = 5; // 默认创建5个子进程

class ProcessPool
{
public:
    ProcessPool(int num = gdefaultnum)
        : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }

    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if(n > 0)
            {
                if(n != sizeof(code)) 
                    continue;
                std::cout << "子进程[" << getpid() << "]收到一个任务码" << std::endl;
                // 根据任务码执行对应任务
                _tm.Execute(code);
            }
            else if(n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }

    bool Start()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1. 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            // 2. 创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // 子进程
                // 3. 关闭不需要的读写端
                close(pipefd[1]);
                _cm.CloseAll(); // 关闭除了父进程的写端
                Work(pipefd[0]); // 子进程需要处理父进程派发的任务
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                // 3. 关闭不需要的读写端
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid); // 父进程将创建的子进程和对应的管道插入到数组中管理起来make
            }
        }
        return true;
    }

    void Run()
    {
        // 1. 获取任务码
        int taskcode = _tm.Code();

        // 2. 选择一个管道写入，让子进程读取然后执行
        auto& c = _cm.Select();
        std::cout << "选择了一个子进程:" << c.Name() << std::endl;
        c.Send(taskcode);
        std::cout << "发送了一个任务码:" << taskcode << std::endl;
        
    }

    void Stop()
    {
        // 关闭文件描述符，回收子进程
        // _cm.CloseFd();
        // _cm.WaitSubid();
        _cm.CloseAndWait();
    }

    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};

#endif